﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class companylist : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString(); ;
    }
    
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            string userid = ""; string compid = "";
            lblMessage.Text = "";
            setPageTitle();
            if (Request.QueryString.Count > 0)
            {
                if (getQueryString("clist") != "" && getQueryString("clist") == "1")
                {
                    userid = Session["userid"].ToString();
                    compid = Session["company_id"].ToString();
                    lbl_header.Text = "Select a company";
                    loadcompanylist(userid, compid);
                }
                else
                {
                    userid = Session["userid"].ToString();
                    compid = Session["company_id"].ToString();
                    if (userid.Trim() == "" || compid.Trim() == "")
                        lblMessage.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                    else
                    {   //Process login
                        LoginProcess LP = new LoginProcess();
                        string sCompanyURL = LP.getCompanyHomePage(compid, userid, "");
                        if (sCompanyURL != "")
                            Response.Redirect(sCompanyURL);
                        else
                            lblMessage.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            lblMessage.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
            LogWriter.WriteLog("Error in companylist - Page Load : " + ex.Message);
        }
    }
    private string getQueryString(string key)
    {
        if (Request.QueryString[key] == null)
            return "";
        return Request.QueryString[key].ToString();
    }
    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }

    #region loadcompanylist
    private void loadcompanylist(string userid, string compid)
    {
        HDDatabase HDD = new HDDatabase();
        try
        {
            if (Session["servercon"] != null)
                if (Session["servercon"].ToString() != "")
                    HDD = new HDDatabase(Session["servercon"].ToString());
            DataTable dtCompany = HDD.GetDataTable("select * from ngcompany where company_id in (select company_id from ngcompanyuser where user_id = '" + userid.Replace("'", "''") + "') order by company_name asc, company_id asc;");
            if (dtCompany.Rows.Count > 0)
            {
                if (dtCompany.Rows.Count == 1)
                    Response.Redirect("companylist.aspx?req=1");
                else
                {
                    HtmlTable ht = new HtmlTable();
                    //ht.CellPadding = 3;
                    ht.CellSpacing = 0;
                    HtmlTableRow htr = null;
                    HtmlTableCell htc = null;
                    foreach (DataRow dr in dtCompany.Rows)
                    {
                        htr = new HtmlTableRow();
                        htr.ID = "tr_com_" + dr["af_row_id"].ToString();
                        htc = new HtmlTableCell();
                        string sCompanyLogo = getCompanyLogo(dr["af_row_id"].ToString());
                        htc.Controls.Add(new LiteralControl(sCompanyLogo));
                        htr.Controls.Add(htc);
                        
                        htc = new HtmlTableCell();
                        if (compid == dr["company_id"].ToString())
                        {
                            string sCompanyLink = @"<a href=""companylist.aspx?req=1""><font color=""blue"">" + (dr["company_name"].ToString() == "" ? dr["company_id"].ToString() : dr["company_name"].ToString()) + "</font></a>";
                            htc.Controls.Add(new LiteralControl(sCompanyLink));
                            htc.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
                            htr.Controls.Add(htc);
                        }
                        else
                        {
                            string sCompanyLink = "<span style='text-decoration:underline;cursor:pointer;' onclick=\"javascript:getpwd(this, '" + dr["af_row_id"].ToString() + "');\"><font color=\"blue\">" + (dr["company_name"].ToString() == "" ? dr["company_id"].ToString() : dr["company_name"].ToString()) + "</font></span>";
                            htc.Controls.Add(new LiteralControl(sCompanyLink));

                            #region for Password security
                            HtmlTable ht_pwd = new HtmlTable();
                            HtmlTableRow htr_pwd = new HtmlTableRow();
                            HtmlTableCell htc_pwd = new HtmlTableCell();

                            Label lbl = new Label();
                            lbl.CssClass = "controlLabelFont";
                            lbl.Text = "Password:";
                            htc_pwd.Controls.Add(lbl);
                            htr_pwd.Controls.Add(htc_pwd);
                            ht_pwd.Controls.Add(htr_pwd);

                            htr_pwd = new HtmlTableRow();
                            htc_pwd = new HtmlTableCell();
                            
                            TextBox txt = new TextBox();
                            txt.ID = "txt_com_" + dr["af_row_id"].ToString();
                            txt.CssClass = "controlFont";
                            txt.TextMode = TextBoxMode.Password;
                            htc_pwd.Controls.Add(txt);
                            HiddenField hf = new HiddenField();
                            hf.ID = "hf_com_" + dr["af_row_id"].ToString();
                            hf.Value = dr["company_id"].ToString();
                            htc_pwd.Controls.Add(hf);
                            htr_pwd.Controls.Add(htc_pwd);
                            ht_pwd.Controls.Add(htr_pwd);

                            htr_pwd = new HtmlTableRow();
                            htc_pwd = new HtmlTableCell();

                            Button btnLogin = new Button();
                            btnLogin.ID = "btnLogin_" + dr["af_row_id"].ToString();
                            btnLogin.CssClass = "controlLabelFont";
                            btnLogin.Text = "Login";
                            btnLogin.ToolTip = "Login";
                            btnLogin.CausesValidation = false;
                            btnLogin.Click += new EventHandler(btnPwdLogin_Click);
                            htc_pwd.Controls.Add(btnLogin);

                            htc_pwd.Controls.Add(new LiteralControl("&nbsp;"));
                            Button btnReset = new Button();
                            btnReset.ID = "btnReset_" + dr["af_row_id"].ToString();
                            btnReset.CssClass = "controlLabelFont";
                            btnReset.Text = "Cancel";
                            btnReset.ToolTip = "Cancel";
                            btnReset.UseSubmitBehavior = false;
                            //btnReset.CausesValidation = false;
                            btnReset.OnClientClick = "javascript:$('#lblMessage').text('');document.location.href;";
                            htc_pwd.Controls.Add(btnReset);
                            
                            htr_pwd.Controls.Add(htc_pwd);
                            ht_pwd.Controls.Add(htr_pwd);

                            Panel div = new Panel();
                            div.ID = "div_com_" + dr["af_row_id"].ToString();
                            div.Controls.Add(ht_pwd);
                            htc.Controls.Add(div);

                            #endregion
                            
                            htr.Controls.Add(htc);
                        }

                        int intRow = (ht.Rows.Count + 1) % 2;
                        htr.VAlign = "middle";
                        htr.Height = "25px";
                        htr.Attributes.Add("Class", "Grid_Row" + intRow.ToString());
                        htr.Attributes.Add("onMouseOver", "this.className='Grid_Scroll_BG'");
                        htr.Attributes.Add("onMouseOut", "this.className='" + "Grid_Row" + intRow.ToString() + "'");
                        ht.Rows.Add(htr);
                    }
                    td_companylist.Controls.Add(ht);
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error in companylist - loadcompanylist : " + ex.Message);
        }
        finally
        {
            HDD = null;
        }
    }

    private string getCompanyLogo(string sCompanyRowId)
    {
        string sReturn = "<table border='0' cellpadding='0' cellspacing='0' width='236' height='76'><tr><td align=\"center\" valign=\"middle\" style=background:url('images/LightBlue/logo.gif');background-repeat:no-repeat;>&nbsp;</td></tr></table>";
        string temp = "url('images/LightBlue/logo.gif');";
        try
        {
            if (sCompanyRowId != "")
            {
                createCustomLogo(sCompanyRowId);
                DirectoryInfo di = new DirectoryInfo(HttpContext.Current.Server.MapPath(".") + "\\Images\\CustomLogo");
                FileInfo[] fis = di.GetFiles(sCompanyRowId + "*");
                if (fis.Length > 0)
                {
                    temp = "url('images/CustomLogo/" + fis[0].Name + "')";
                    sReturn = "<table border='0' cellpadding='0' cellspacing='0' width='236' height='76'><tr><td align=\"center\" valign=\"middle\" style=background:url('images/CustomLogo/" + fis[0].Name + "');background-repeat:no-repeat;>&nbsp;</td></tr></table>";
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error in companylist - getCompanyLogo : " + ex.Message);
        }
        return sReturn;
    }
    private bool createCustomLogo(string companyRowId)
    {
        HDDatabase hddLogo = null;
        bool ret = false;
        try
        {
            hddLogo = new HDDatabase(HttpContext.Current.Session["servercon"].ToString());
            DataTable dt = hddLogo.GetDataTable("select logo_content,logo_file_name from ngcompany where af_row_id ='" + companyRowId + "'");
            if (dt.Rows.Count > 0)
            {
                if (dt.Rows[0]["logo_content"] != System.DBNull.Value)
                {
                    byte[] imageData = (byte[])dt.Rows[0]["logo_content"];
                    string temp = dt.Rows[0]["logo_file_name"].ToString();
                    //fileName = fileName;//don't know why this existed at the first place.
                    temp = temp.Substring(temp.LastIndexOf("."));
                    FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(".") + "\\Images\\CustomLogo\\" + companyRowId + temp, FileMode.Create);
                    fs.Write(imageData, 0, imageData.Length);
                    fs.Flush(); fs.Close(); fs = null;
                    ret = true;
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error :createCustomLogo()" + e.Message);
        }
        finally
        {
            hddLogo = null;
        }
        return ret;
    }
    #endregion

    void btnPwdLogin_Click(object sender, EventArgs e)
    {
        string userid = "", compid = "", pwd = "", txtRowID = "";
        LoginProcess LP = new LoginProcess();
        try
        {
            Button btn = (Button)sender;
            txtRowID = btn.ID.Substring(btn.ID.LastIndexOf('_') + 1);
            userid = Session["userid"].ToString();
            TextBox txt_PWD = (TextBox)Form1.FindControl("txt_com_" + txtRowID);
            if (txt_PWD != null)
                pwd = txt_PWD.Text;
            HiddenField hf_com = (HiddenField)Form1.FindControl("hf_com_" + txtRowID);
            if (hf_com != null)
                compid = hf_com.Value;
            string sTempUrl = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.LastIndexOf('?') + 1);
            if (LP.UserValidate(compid, userid, pwd))
            {
                Session["company_id"] = compid;
                Response.Redirect(sTempUrl + "req=1");
            }
            else
            {
                AuditLog AL = new AuditLog();
                security hds = new security(userid);
                AL.logUserInModel(compid, userid, false); // Modified by 'Imran Gani' on 25-Nov-2013.
                AL = null;
                hds.HandleLoginAttempts(compid, userid, pwd); // Added by 'Imran Gani' on 25-Nov-2013.
                lblMessage.Text = (hds.Message == null || hds.Message == "" ? "Invalid Password. Please try again." : hds.Message);
                hds = null;
                lblMessage.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;" + lblMessage.Text, true);
                lblMessage.Attributes.Add("class", "Dynamic_PageHeaderRow");
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error in companylist - Page Load : " + ex.Message);
        }
        finally
        {
            LP = null;
        }
    }
    private void setPageTitle()
    {
        try
        {
            if (Session["pageTitle"] != null)
            {
                Page.Header.Title = Session["pageTitle"].ToString();
            }
            else
            {
                if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(".") + "\\maxbloxtitle.ini"))
                {
                    System.IO.StreamReader sr = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(".") + "\\maxbloxtitle.ini");
                    Session["pageTitle"] = sr.ReadLine();
                    Page.Header.Title = Session["pageTitle"].ToString();
                    sr.Close();
                    sr = null;
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in setPageTitle function. Error: " + e.Message);
        }
    }
}